<?php

namespace App\Containers\AppSection\Ban\Actions;

use App\Containers\AppSection\Ban\Tasks\UpdateBanTask;
use App\Containers\AppSection\Log\Tasks\CreateLogTask;
use App\Containers\AppSection\Profile\Tasks\FindLatestProfileByUserIdTask;
use App\Containers\AppSection\User\Tasks\FindUserByIdTask;
use App\Containers\AppSection\User\Tasks\UpdateUserTask;
use App\Ship\Exceptions\BadRequestException;
use App\Ship\Parents\Actions\Action;
use App\Ship\Parents\Requests\Request;

class UnbanUserAction extends Action
{
    public function run($id, Request $request)
    {
        $user = app(FindUserByIdTask::class)->run($id);

        if ($user->isNotBanned()) {
            throw new BadRequestException('Пользователь не был заблокирован!');
        }

        app(UpdateUserTask::class)->run(['ban_id' => null, 'deleted_at' => null], $user->id);

        app(UpdateBanTask::class)->run($user->ban->id, [
            'unbanned_at' => now(),
            'unban_comment' => $request->getInputByKey('comment')
        ]);

        $profile = app(FindLatestProfileByUserIdTask::class)->run($user->id);

        app(CreateLogTask::class)->run($profile->id, "Пользователь №{$user->id} разблокирован (админ)", 'ban_user');
        app(CreateLogTask::class)->run($request->profile()->id, "Пользователь №{$user->id} разблокирован", 'ban_user');
    }
}
